package com.wlcj.plugin.xmlsql;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.IPlugin;
import com.wlcj.util.XmlUtil;

public class XmlSqlPlugin implements IPlugin {
	
	private String[] paths;
	
	public static Map<String, String> sqlMap = new HashMap<String, String>();
	
	public XmlSqlPlugin() {
		this.paths = new String[]{"sql"};
	}
	
	public XmlSqlPlugin(String...paths) {
		this.paths = paths;
	}

	@Override
	public boolean start() {
		for(String path:paths) {
			String fullPath = PathKit.getRootClassPath()+"/"+path;
			File dir = new File(fullPath);
			if(!dir.exists())
				throw new RuntimeException("classpath下没有"+fullPath+"这个目录");
			else {
				File[] files = dir.listFiles();
				for(File file:files) {
					String fileName = file.getName();
					if(!fileName.endsWith(".xml")) continue;
					Sqls sqls = XmlUtil.toBeanFromFile(file, Sqls.class);
					for(Sql sql:sqls.getSqlList()) {
						String key = fileName.substring(0, fileName.indexOf(".xml"))+"."+sql.getId();
						sqlMap.put(key, sql.getText());
					}
				}
			}
		}
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}

}
